/**
 * Application Layout
 * by Jozef Sakalos, aka Saki
 * http://extjs.com/learn/Tutorial:Application_Layout_for_Beginners
 */
// reference local blank image
//Ext.BLANK_IMAGE_URL = '../extjs/resources/images/default/s.gif';

// create namespace
Ext.namespace('pacp');

// create application
pacp.app = function(){
    // do NOT access DOM from here; elements don't exist yet
    
    // private variables
    //    var run_store; //runs table
    //    var detail_store;//details table
    //    var run_tpl;//template for run
    //    var detail_tpl;//template for detail
    //    var run_panel; //run list panel
    //    var detail_panel;//detail list panel
    // private functions
    // create the Data Store
    var run_store = new Ext.data.JsonStore({
        root: 'runs',
        totalProperty: 'totalcount',
        idProperty: 'RunID',
        id: 'RunID',
        fields: ['RunID', 'City', 'Owner', 'Customer', 'Surveyor_Name', 'Upstream_MH', 'Downstream_MH', 'PIPETECHID', {
            name: 'Date',
            type: 'date',
            dateFormat: 'Ymd'
        }, 'Time', 'Street', 'Direction_of_Survey', 'dia', 'Material', 'Weather', 'Pre-Cleaning', 'Shape', 'Length_Surveyed', 'Additional_Info', 'len2'],
        baseParams: {
            limit: 20
        },
        
        // load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: new Ext.data.HttpProxy({
            url: '/run',
            method: 'GET'
        })
    });//end of run store
    var detail_store = new Ext.data.JsonStore({
        root: 'details',
        totalProperty: 'totalcount',
        idProperty: 'DetailID',
        id: 'DetailID',
        fields: ['DetailID', 'RunID', 'Footage', 'VideoFrameNumber', 'ConditionCode', 'Continuous', 'Position_From', 'Position_To', 'Percentage', 'Comment', 'Dimension1', 'Dimension2', 'foot'],
        baseParams: {
            limit: 20
        },
        
        // load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: new Ext.data.HttpProxy({
            url: '/detail',
            method: 'GET'
        })
    });//end of detail store
    // Custom rendering Template for the View
    var run_tpl = new Ext.XTemplate('<tpl for=".">', '<div class="run-summary">', 
	'<span class = "right"> {Date:date("M j, Y")}<br/>{Weather}, {Pre-Cleaning}</span>',
	'<h4 style="color:blue;" class="{Direction_of_Survey}">{PIPETECHID}</h4>', 
	'<p>@{Street}<br/>',
	'{dia}in. {Material}, {len2} ft </p><br/>', 
	'<tpl if="Additional_Info!=null"><span class="comment">{Additional_Info}</span><br/></tpl>', 
	'</div></tpl>');
    
    var detail_tpl = new Ext.XTemplate('<tpl for=".">', '<div class="defect-summary">', '<h3><span>', '@{foot}ft <br/>', '<tpl if="Position_From!=null">{Position_From}</tpl>', '<tpl if="Position_To!=null">-{Position_To}</tpl>', '</span>', '<tpl if="this.startWith(Continuous, &quot;S&quot;)==true"><p class="Downstream">{ConditionCode}({Continuous})</p></tpl>', '<tpl if="this.startWith(Continuous, &quot;F&quot;)==true"><p class="Upstream">{ConditionCode}({Continuous})</p></tpl>', '<tpl if="Continuous==null">{ConditionCode}</tpl>', '<tpl if="Position_From!=null"><img style="align:right;" alt="text" src="clock.jpg"/></tpl>', '</h3>', '<tpl if="Comment!=null">{Comment}</tpl>', '<tpl if="Comment==null"><br/></tpl>', '</div></tpl>', {
        // XTemplate configuration:
        compiled: true,
        disableFormats: true,
        // member functions:
        startWith: function(x, y){
            if (x == null) {
                return false
            }
            else {
                return x.substr(0, 1) == y;
            }
        }
    });//end of detail_tpl
    //  Choice of using a template instead of a grid
    //    var run_panel = new Ext.Panel({
    //        //        applyTo: 'search-panel',
    //        
    //        height: 600,
    //        width: 350,
    //        autoScroll: true,
    //        
    //        items: new Ext.DataView({
    //            tpl: run_tpl,
    //            store: run_store,
    //            itemSelector: 'div.search-item'
    //        }),
    //        
    //        
    //        
    //        tbar: new Ext.PagingToolbar({
    //            store: run_store,
    //            pageSize: 10,
    //            displayInfo: true,
    //            displayMsg: '{0} - {1} of {2}',
    //            emptyMsg: "No inspection to display"
    //        })
    //    });//end of run_panel
    /*
     * The Grid panel of runs
     *
     */
    // pluggable renders
    function renderSummary(value, p, record){
    
    	if (record.data.Additional_Info==null) {
			add_info = '';
		} else {
			add_info = record.data.Additional_Info;
		};
    
        return String.format('<h3><a class="{0}">{6}</a><br/> @  <b>{1}</b><br/> {2}in. {3}, {4} ft </h3>{5}', record.data.Direction_of_Survey, record.data.Street, record.data.dia, record.data.Material, record.data.len2, add_info, record.data.PIPETECHID);
    };//end of renderSummary
    function renderDate(value, p, r){
        return String.format('{0}<br/> {1}, {2}', value.dateFormat('M j, Y'), r.data.Weather, r.data['Pre-Cleaning']);
    }; //end of renderDate
    function renderDetail(value, p, r){
    
        if (r.data.Continuous) {
            c_flag = r.data.Continuous.substr(0, 1);
        }
        else {
            c_flag = null;
        };
        
        html = '';
        if (c_flag == 'S') {
            html = '<p class="Downstream">' + r.data.ConditionCode + '(' + r.data.Continuous + ')</p>';
        }
        else 
            if (c_flag == 'F') {
                html = '<p class="Upstream">' + r.data.ConditionCode + '(' + r.data.Continuous + ')</p>';
            }
            else {
                html = r.data.ConditionCode;
            };
        
        if (r.data.Comment) {
            c = r.data.Comment;
        }
        else {
            c = ''
        };
        return '<h3>' + html + '</h3>' + c;
    }; //end of renderDetail
    function renderFootage(value, p, r){
        t = '';
        if (r.data.Position_From) {
            t = r.data.Position_From;
        };
        if (r.data.Position_To) {
            t = t + '-' + r.data.Position_To;
        };
        return '@' + r.data.foot + 'ft <br/> ' + t
        
    };
    
    
    
    
    var run_panel = new Ext.grid.GridPanel({
        width: 350,
        store: run_store,
        trackMouseOver: true,
        disableSelection: true,
        loadMask: true,
        
        // grid columns
        columns: [{
            header: "Summary",
            dataIndex: 'PIPETECHID',
            width: 250,
            renderer: renderSummary,
            sortable: true
        }, {
            header: "Date",
            dataIndex: 'Date',
            width: 80,
            renderer: renderDate,
            
            sortable: true
        }],
        
        // customize view config
        sm: new Ext.grid.RowSelectionModel({
            singleSelect: true
        }),
        
        viewConfig: {
            forceFit: true
        },
        
        // paging bar on the bottom
        tbar: new Ext.PagingToolbar({
            pageSize: 25,
            store: run_store,
            displayInfo: true,
            displayMsg: 'Runs {0} - {1} of {2}',
            emptyMsg: "No Runs to display"
        })
    });//end of run panel as grid
    var detail_panel = new Ext.grid.GridPanel({
        width: 350,
        height: 400,
        store: detail_store,
        trackMouseOver: true,
        disableSelection: true,
        loadMask: true,
        
        // grid columns
        columns: [{
            header: "Summary",
            dataIndex: 'PIPETECHID',
            width: 250,
            renderer: renderSummary,
            sortable: true
        }, {
            header: "Date",
            dataIndex: 'Date',
            width: 80,
            renderer: renderDate,
            
            sortable: true
        }],
        
        // customize view config
        sm: new Ext.grid.RowSelectionModel({
            singleSelect: true
        }),
        
        viewConfig: {
            forceFit: true
        },
        
        // paging bar on the bottom
        tbar: new Ext.PagingToolbar({
            pageSize: 25,
            store: run_store,
            displayInfo: true,
            displayMsg: 'Runs {0} - {1} of {2}',
            emptyMsg: "No Runs to display"
        })
    });//end of detail panel as grid
    var detail_panel = new Ext.Panel({
        //        applyTo: 'detail-search-panel',
        title: 'PACP Search',
        height: 600,
        width: '100%',
        autoScroll: true,
        
        items: new Ext.DataView({
            tpl: detail_tpl,
            store: detail_store,
            itemSelector: 'div.search-item'
        }),
        tbar: ['RunID: ', ' ', new Ext.ux.form.SearchField({
            store: detail_store,
            width: 200
        })],
        
        bbar: new Ext.PagingToolbar({
            store: detail_store,
            pageSize: 20,
            displayInfo: true,
            displayMsg: '{0} - {1} of {2}',
            emptyMsg: "No inspection to display"
        })
    }); //end of detail panel
    var header = new Ext.Panel({
        border: false,
        layout: 'anchor',
        region: 'north',
        cls: 'docs-header',
        height: 60,
        items: [{
            xtype: 'box',
            el: 'header',
            border: false,
            anchor: 'none -25'
        }, new Ext.Toolbar({
            cls: 'top-toolbar',
            items: ['PipetechID: ', new Ext.ux.form.SearchField({
                store: run_store,
                width: 200
            })]
        })]
    });//end of header
    var tabs = new Ext.TabPanel({
        resizeTabs: true, // turn on tab resizing
        minTabWidth: 115,
        tabWidth: 135,
        activeTab: 0,
        
        enableTabScroll: true,
        defaults: {
            autoScroll: true,
			autoHeight: true
        },
        
        plugins: new Ext.ux.TabCloseMenu(),
        items: {
            id: 'welcome-panel',
            title: 'PACP Viewer Home',
            autoLoad: 'welcome.htm',
            height: 800,
			autoScroll: true,
            
            closable: false
        }
    });
    
    
    
    // public space
    return {
        // public properties, e.g. strings to translate
        
        // public methods
        init: function(){
            //viewport 
            var viewport = new Ext.Viewport({
                layout: 'border',
                items: [header, {
                    region: 'south',
                    border: true,
                    html: '<div style="text-align: center;font-size: 80%;color:black;">Miller Kelton I&I Project - PACP Data Viewer by Mel Meng May 2009, <a href="http://www.dlz.com">DLZ</a>. ymeng@dlz.com<div>'
                
                }, {
                    region: 'west',
                    layout: 'fit',
                    split: true,
                    width: 350,
                    minSize: 175,
                    maxSize: 400,
                    collapseMode: 'mini',
                    collapsible: true,
                    autoScroll: false,
                    
                    
                    //                    margins: '0 0 5 5',
                    //                    cmargins: '0 5 5 5',
                    
                    layoutConfig: {
                        animate: true
                    },
                    items: [run_panel]
                }, {
                    region: 'center',
					layout: 'fit',
                    border: false,
                    collapsible: true,
					autoScroll: true,
                    id: 'img-detail-panel',
                    split: true,
                    width: 150,
                    minWidth: 150,
                    maxWidth: 250,
                    
                    items: [tabs]
                    //                    margins: '0 0 5 5',
                    //                    cmargins: '0 5 5 5'
                }]
            });//end of viewport
            run_store.load({
                params: {
                    start: 0,
                    limit: 20
                }
            });//end of run_store.load
            run_panel.getSelectionModel().on('rowselect', function(sm, rowIdx, r){
            	//when the run is clicked
                var tab = Ext.getCmp('tab' + r.data.RunID);
                if (tab) {
					//if already exist
                    tabs.setActiveTab(tab)
                }
                else {
					//html of the run
                    html_text = run_tpl.applyTemplate(r.data);
					//html for the flash object
                    so = new SWFObject('/public/lib/jwplayer/player.swf', 'media' + r.data.RunID, '400', '300', '9');
                    so.addParam('allowfullscreen', 'true');
                    so.addParam('allowscriptaccess', 'always');
                    so.addParam('wmode', 'opaque');
                    so.addVariable('file', '/' + r.data.PIPETECHID + '.flv');
                    flash_html = so.getSWFHTML();
                    
                    
                    //static store to hold data for each inspection, so I can have more than one defects list
                    var detail_tmp_store = new Ext.data.JsonStore({
                        root: 'details',
                        totalProperty: 'totalcount',
                        idProperty: 'DetailID',
                        id: 'DetailID',
                        fields: ['DetailID', 'RunID', 'VideoFrameNumber', 'Footage', 'ConditionCode', 'Continuous', 'Position_From', 'Position_To', 'Percentage', 'Comment', 'Dimension1', 'Dimension2', 'foot'],
                        baseParams: {
                            limit: 20
                        }
                    });//end of detail tmp store
                    //grid panel on each tab
                    var detail_tab_panel = new Ext.grid.GridPanel({
                        width: 350,
                        title: 'Defects List:',
                        id: 'table' + r.data.RunID,
                        store: detail_tmp_store,
                        trackMouseOver: true,
                        disableSelection: true,
                        loadMask: true,
                        
                        // grid columns
                        columns: [{
                            header: "Summary",
                            dataIndex: 'ConditionCode',
                            width: 250,
                            renderer: renderDetail,
                            sortable: true
                        }, {
                            header: "Footage",
                            dataIndex: 'foot',
                            width: 80,
                            renderer: renderFootage,
                            
                            sortable: true
                        }],
                        
                        // customize view config
                        sm: new Ext.grid.RowSelectionModel({
                            singleSelect: true
                        }),
                        
                        viewConfig: {
                            forceFit: true,
							autoScroll: true
                        }
                    });//end of run panel as grid
                    
					//when the defect is clicked
                    detail_tab_panel.getSelectionModel().on('rowselect', function(sm, rowIdx, r){
                        var defectPanel = Ext.getCmp('defect' + r.data.RunID);
                        detail_tpl.overwrite(defectPanel.body, r.data);
                        
                        var player = document.getElementById('media' + r.data.RunID);
						//make sure it plays, otherwise the seek won't work
                        player.sendEvent("PLAY", "true");
						
                        player.sendEvent('SEEK', r.data.VideoFrameNumber / 29.9)
                        
                    });//end of detail_tab_panel click event
					
                    tabs.add({
                        title: r.data.PIPETECHID,
                        id: 'tab' + r.data.RunID,
                        
                        items: [{
                            layout: 'border',
                            height: 600,
							autoScroll: true,
                            items: [{
                                region: 'north',
                                width: 400,
                                height: 70,
                                border: false,
                                html: html_text
                            }, {
                                region: 'west',
								layout: 'fit',
                                border: false,
                                width: 400,
                                margins: '0 0 0 0',
                                cmargins: '0 0 0 5',
                                bodyStyle: 'padding:10px;',
                                autoScroll: true,
                                items: [detail_tab_panel]
                            
                            }, {
                                region: 'center',
                                border: false,
                                margins: '0 0 0 0',
                                cmargins: '5 5 5 5',
                                bodyStyle: 'padding:10px;',

                                
                                items: [{
                                    id: 'defect' + r.data.RunID,
                                    height: 100,
                                    border: false,
                                    html: '<=Click on the defect to show details.'
                                }, {
                                    height: 400,
                                    id: 'mediaspace' + r.data.RunID,
                                    border: false,
                                    html: flash_html
                                }]
                            }]
                        }],
                        closable: true
                    }).show()//end tab add

                };
                Ext.Ajax.request({
                    waitMsg: 'Accessing Data...',
                    url: '/detail',
                    method: 'GET',
                    params: {
                        limit: 20,
                        start: 0,
                        query: r.data.RunID
                    },
                    success: function(response){
                        var obj = Ext.util.JSON.decode(response.responseText);
                        detail_tmp_store.loadData(obj, false);
                        detail_tab_panel.setTitle(obj.totalcount + ' Defects');
                    }
                });//end of Ajax request
            });
            
        }
    };
}(); // end of app
// end of file


